import { filedConfig } from '@/form_config/const'
import { defineStore } from 'pinia'

// 基础配置
function getBaseConfig(prop: Record<string, any>) {
  const base: Record<string, any> = {}
  for (const key in prop) {
    base[key] = prop[key].value
  }
  return base
}

function getConfig(label: string) {
  const config: Record<string, any> = filedConfig
  const base = getBaseConfig(config[label].properties)
  return {
    ...base
  }
}

// 表单
export const useFormStore = defineStore({
  id: 'formStore',
  state: (): any => ({
    formIndex: -1,
    fieldList: []
  }),
  getters: {
    config(state) {
      return state.fieldList[state.formIndex] || {}
    },
    filedConfig: (state) => {
      return filedConfig[state.config.type]
    }
  },
  persist: true,
  actions: {
    // 添加一个组件
    addFormItem({ type, name }: any) {
      this.fieldList.push({
        ...getConfig(type),
        label: name,
        type,
        name
      })
      this.formIndex++
    },
    setFormType(type: string) {
      this.formType = type
    }
  }
})
